<template>
  <div id="fatherBox">
    <!-- 搜索框 -->
    <div class="header-search">
		  <input type="text" placeholder="输入城市名或拼音" class="header-search-input" v-model="keyWords">
	  </div>
    <!-- 显示匹配项 -->
    <div class="item-match" v-show="keyWords" ref="wrapper">
      <ul>
        <li class="search-item" 
          v-for="item of list" 
          :key="item.id"
          @click="changeIndex(item.name)">
          {{item.name}}
        </li>
        <li class="search-item" v-show="hasNoData">没有匹配到数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
  name: 'citySearch',
  data () {
    return {
      keyWords: '',//与输入框双向绑定检索关键词
      list: [],
      // status: '', 
      timer: null,
    }
  },
  methods: {
    changeIndex(name) {
      this.$store.commit('changCity', name)
      this.$router.push('/')
    }
  },
  mounted () {
		this.$nextTick(() => {// 用于无滑动条滑动效果
      let bscrollDom = this.$refs.wrapper;
      this.aBScroll = new BScroll(bscrollDom,{})
    })  
  },
  props: {
    city: Object,
  },
  computed: {
    hasNoData () {//有输入内容但是无匹配项目 控制提示信息的显示
      return !this.list.length
    }
  },
  watch: {
    keyWords () {//监听输入框中的内容，然后将输入的内容与JSON中数据比对  将匹配到的项单独存入一个数组
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWords.length) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => { //定时器函数节流
        const matchKey = []
      for (let i in this.city) {//拿到JSON中的键值
        this.city[i].forEach(element => {
          if (element.spell.indexOf(this.keyWords) > -1 || element.name.indexOf(this.keyWords) > -1) {
            matchKey.push(element)
          }
        });
      }
      this.list = matchKey
      },100)
      
    },
  },
}
</script>
<style scoped>
/* #fatherBox {
  position: relative;
} */
.header-search {/*搜索框外层盒子*/
	height: .72rem;
	padding: 0 .1rem;
	background-color: #00bcd4;
}
.header-search-input {/*搜索框*/
	width: 100%;
	height: .62rem;
	line-height: .62rem;
	text-align: center;
	box-sizing: border-box;
	padding:  .1rem;
	border-radius: .12rem;
	color: #666;
}
.item-match {/*匹配框盒子*/
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0; 
  background: #eee;
}
.search-item {
  line-height: .62rem;
  padding-left: .2rem;
  background: #fff;
  color: #666;
}
      
</style>


